import { ref, reactive, computed } from 'vue'
import { VxeColumnPropTypes, VxeInputProps } from 'vxe-pc-ui'
import type { VxeTableInstance, VxeTablePropTypes } from 'vxe-table'
import { useAppStore } from '@/store/modules/app'
import { generateUUID } from '@/utils'

export const useVxeEditTable = <T>() => {
  const { t } = useI18n() // 国际化

  const appStore = useAppStore()
  const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)
  const tableRef = ref<VxeTableInstance>()
  const tableData = ref<T[]>([])
  const disabledEdit = ref(false)
  const editConfig = reactive<VxeTablePropTypes.EditConfig<T>>({
    trigger: 'click',
    mode: 'row',
    beforeEditMethod() {
      return !disabledEdit.value
    }
  })

  const textEditRender = reactive<VxeColumnPropTypes.EditRender<T, VxeInputProps>>({
    name: 'VxeInput',
    autoFocus: '.vxe-input--inner',
    placeholder: t('reviewApplyInfo.clickInputText')
  })

  const numberEditRender = reactive<VxeColumnPropTypes.EditRender<T, VxeInputProps>>({
    name: 'VxeNumberInput',
    props: { type: 'integer' },
    placeholder: t('reviewApplyInfo.clickInputText')
  })

  const floatEditRender = reactive<VxeColumnPropTypes.EditRender<T, VxeInputProps>>({
    name: 'VxeNumberInput',
    props: { type: 'float', min: 0 },
    placeholder: t('reviewApplyInfo.clickInputText')
  })

  const formatSelect = (value: any) => {
    if (value === '1') {
      return t('common.yes')
    }
    if (value === '0') {
      return t('common.yes')
    }
    return ''
  }

  const addRow = async (defaultRecord: Omit<T, 'id'>, editCell = 'name') => {
    const $table = tableRef.value
    if ($table) {
      const record = { ...defaultRecord, id: generateUUID() }
      const { row: newRow } = await $table.insertAt(record, -1)
      await $table.setEditCell(newRow, editCell)
    }
  }

  const removeRow = async (row: T) => {
    const $table = tableRef.value
    if ($table) {
      await $table.remove(row)
    }
  }

  const getTableData = () => {
    const $table = tableRef.value
    if ($table) {
      const { tableData } = $table.getTableData()
      return tableData.map((item) => {
        delete item._X_ROW_KEY
        delete item.action
        return item
      })
    } else {
      return tableData.value
    }
  }

  return {
    disabledEdit,
    tableRef,
    editConfig,
    tableData,
    vxeTableSize,
    textEditRender,
    numberEditRender,
    floatEditRender,
    formatSelect,
    addRow,
    removeRow,
    getTableData
  }
}
